﻿using System;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
using TestStepsEditor.Actions;
using TestStepsEditor.Viewers.Data;
using TestStepsEditor.Forms;

namespace TestStepsEditor
{
    public partial class MainForm : Form
    {
        public event EventHandler<ExportEventArgs> Export;
        public event EventHandler<ExportEventArgs> NewForm;
        public event EventHandler<ExportEventArgs> CopyRows;
        public event EventHandler<ExportEventArgs> PasteRows;

        #region Variables

        //Variables used throughout the app
        private bool formChanged;
        public SharedData Data { get; set; }

        #endregion

        #region Constructors

        public MainForm()
        {
            LoadForm();
        }

        public MainForm(int testCaseId)
        {
            LoadForm();
            Data.WorkItemID = testCaseId;
            Data = LoadData.LoadGridViewData(Data);
            workItemGridView = Data.GridView;
            contextMenuStrip.Visible = false;
            SetLabels(Data.WorkItemAttributes);
        }

        #endregion

        #region Methods

        #region Form Actions

        #region Menu Clicks

        private void tsmAddAttachment_Click(object sender, EventArgs e)
        {
            var form = new AttachmentForm(Data);
            form.Show();
            formChanged = true;
        }

        private void tsmExportRows_Click(object sender, EventArgs e)
        {
            Data.GridView = workItemGridView;
            var args = new ExportEventArgs(Data);

            var evnt = Export;
            if (evnt != null)
                evnt(this, args);
            formChanged = true;
        }

        private void tsmDeleteRows_Click(object sender, EventArgs e)
        {
            Data.StepsCollection = Rows.Delete(Data);
            formChanged = true;
        }

        private void tsmSimpleStep_Click(object sender, EventArgs e)
        {
            Data.GridView = workItemGridView;
            Data = Rows.InsertSimpleStep(Data);
            workItemGridView = Data.GridView;
        }

        private void tsmSharedStep_Click(object sender, EventArgs e)
        {
            if (workItemGridView.RowCount > 0)
            {
                var form = new SharedStepIDForm();
                form.ShowDialog();
                if (form.ID != 0)
                {
                    Data.GridView = workItemGridView;
                    Data = Rows.InsertSharedStep(form.ID, Data);
                    workItemGridView = Data.GridView;
                    Refresh();
                }
            }
        }

        private void tsmViewLinkedTestCases_Click(object sender, EventArgs e)
        {
            if (workItemGridView.CurrentRow == null) return;
            var testCaseForm = new LinkedTestCasesForm(Data.TestProject,
                                                       workItemGridView.Rows[workItemGridView.CurrentRow.Index].Cells[4]
                                                           .Value.ToString());
            testCaseForm.Show();
        }

        private void tsmOpenSharedStep_Click(object sender, EventArgs e)
        {
            var form = new MainForm();

            if (workItemGridView.CurrentRow != null)
            {
                form.newButton.Visible = false;
                form.Show();
                int workItemId =
                    Convert.ToInt32(
                        workItemGridView.Rows[workItemGridView.CurrentRow.Index].Cells["SharedStepNumber"].Value);
                form.workItemTextBox.Text = workItemId.ToString();
                form.loadButtonClick_Click(null, null);
                form.contextMenuStrip.Visible = false;
                form.workItemGridView.Refresh();
                form.workItemGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
            }
        }

        private void tsmDeleteSharedStep_Click(object sender, EventArgs e)
        {
            Data.StepsCollection = Rows.Delete(Data);
            formChanged = true;
        }

        private void tsmCopySelectedRows_Click(object sender, EventArgs e)
        {
            var args = new ExportEventArgs(Data);

            var evnt = CopyRows;
            if (evnt != null)
                evnt(this, args);
            formChanged = true;
        }

        private void tsmInsertCopiedRows_Click(object sender, EventArgs e)
        {
            var args = new ExportEventArgs(Data);

            var evnt = PasteRows;
            if (evnt != null)
                evnt(this, args);
            formChanged = true;
        }

        private void tsmProperties_Click(object sender, EventArgs e)
        { 
            LoadData.LoadProperties(Data);
        }

        #endregion

        #region Button Clicks

        private void newButton_Click(object sender, EventArgs e)
        {
            var args = new ExportEventArgs(Data);

            var evnt = NewForm;
            if (evnt != null)
                evnt(this, args);
            formChanged = true;
        }

        private void saveButtonClick_Click(object sender, EventArgs e)
        {
            Data = WorkItems.Save(Data);
            formChanged = false;
        }

        private void loadButtonClick_Click(object sender, EventArgs e)
        {
            int workItemId;
            Data = new SharedData();
            Data.WorkItemAttributes = new WorkItemAttributes();
            if (!Int32.TryParse(workItemTextBox.Text, out workItemId))
                return;
            Data.GridView = workItemGridView;
            Data.WorkItemID = workItemId;
            Data = LoadData.LoadGridViewData(Data);
            if (Data != null)
            {
                workItemGridView = Data.GridView;
                contextMenuStrip.Visible = false;
                SetLabels(Data.WorkItemAttributes);
            }
            Text = @"TCE 2010 Total Steps " + workItemGridView.Rows.Count;
        }

        private void changeProjectButtonClick_Click(object sender, EventArgs e)
        {
            TfsTeamProjectCollection tfsProjectCollection;
            ITestManagementTeamProject testProject;
            ServerSettings.LoadProjectSelectionFromUser(out tfsProjectCollection, out testProject);
            if (testProject != null)
                projectLabel.Text = tfsProjectCollection.Name + @" " + testProject.WitProject.Name;

            // clear current test info
            if (Data.StepsCollection != null)
                Data.Clear();
        }

        private void insertButtonClick_Click(object sender, EventArgs e)
        {
            Data.GridView = workItemGridView;
            Data = Rows.InsertSimpleStep(Data);
            workItemGridView = Data.GridView;
        }

        private void addSharedStepsButtonClick_Click(object sender, EventArgs e)
        {
            if (workItemGridView.RowCount > 0)
            {
                var form = new SharedStepIDForm();
                form.ShowDialog();
                if (form.ID != 0)
                {
                    Data.GridView = workItemGridView;
                    Data = Rows.InsertSharedStep(form.ID, Data);
                    workItemGridView = Data.GridView;
                    Refresh();
                }
            }
        }

        private void deleteButtonClick_Click(object sender, EventArgs e)
        {
            Data.StepsCollection = Rows.Delete(Data);
            formChanged = true;
        }

        #endregion

        #region Form Clicks and Closing

        private void WorkItemTextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                loadButtonClick_Click(null, null);
        }

        private void TestStepsGridViewCurrentCellChanged(object sender, EventArgs e)
        {
            rowLabel.Text = workItemGridView.CurrentRow != null
                                ? String.Format("Row:{0}", workItemGridView.CurrentRow.Index + 1)
                                : @"Row:";
            Text = @"TCE 2010 Total Steps " + workItemGridView.Rows.Count;
        }

        private void TestStepsGridViewCellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (workItemGridView.CurrentCell != null)
            {
                if (workItemGridView.CurrentCell.ReadOnly && e.Button == MouseButtons.Right)
                {
                    contextMenuStrip.Visible = true;
                    tsmOpenSharedStep.Visible = true;
                    tsmViewLinkedTestCases.Visible = true;
                    tsmDeleteSharedStep.Visible = true;
                    toolStripSeparator3.Visible = true;
                    tsmInsertStep.Visible = false;
                    tsmSharedStep.Visible = false;
                    tsmExportRows.Visible = false;
                    tsmDeleteRows.Visible = false;
                    tsmSimpleStep.Visible = false;
                    tsmAddAttachment.Visible = false;
                    tsmCopySelectedRows.Visible = false;
                    tsmInsertCopiedRows.Visible = false;
                    toolStripSeparator1.Visible = false;
                    toolStripSeparator2.Visible = false;
                    {
                        if (workItemGridView.CurrentRow != null)
                            tsmOpenSharedStep.Text = @"Edit Shared Step - " +
                                                     workItemGridView.CurrentRow.Cells["SharedStepNumber"].Value;
                    }
                    contextMenuStrip.Show(MousePosition);
                }
                if (workItemGridView.CurrentCell.ReadOnly == false && e.Button == MouseButtons.Right)
                {
                    contextMenuStrip.Visible = true;
                    tsmExportRows.Visible = true;
                    tsmDeleteRows.Visible = true;
                    tsmOpenSharedStep.Visible = false;
                    tsmViewLinkedTestCases.Visible = false;
                    tsmDeleteSharedStep.Visible = false;
                    tsmInsertStep.Visible = true;
                    tsmSimpleStep.Visible = true;
                    tsmSharedStep.Visible = true;
                    tsmAddAttachment.Visible = true;
                    tsmCopySelectedRows.Visible = true;
                    tsmInsertCopiedRows.Visible = true;
                    toolStripSeparator1.Visible = true;
                    toolStripSeparator2.Visible = true;
                    toolStripSeparator3.Visible = false;
                    contextMenuStrip.Show(MousePosition);
                }
                if (e.Button == MouseButtons.Left)
                {
                    contextMenuStrip.Visible = false;
                    tsmExportRows.Visible = false;
                    tsmOpenSharedStep.Visible = false;
                    tsmViewLinkedTestCases.Visible = false;
                    tsmDeleteRows.Visible = false;
                    tsmInsertStep.Visible = false;
                    tsmSimpleStep.Visible = false;
                    tsmSharedStep.Visible = false;
                    tsmAddAttachment.Visible = false;
                    tsmDeleteSharedStep.Visible = false;
                    tsmCopySelectedRows.Visible = false;
                    tsmInsertCopiedRows.Visible = false;
                    toolStripSeparator1.Visible = false;
                    toolStripSeparator2.Visible = false;
                    toolStripSeparator3.Visible = false;
                }
                if (workItemGridView.CurrentRow != null)
                    if (workItemGridView.CurrentCell.RowIndex !=
                        workItemGridView.Rows.GetLastRow(DataGridViewElementStates.None))
                        if (workItemGridView.CurrentRow.ReadOnly &&
                            (workItemGridView.Rows[workItemGridView.CurrentRow.Index + 1].ReadOnly == false))
                        {
                            tsmInsertStep.Visible = true;
                            tsmSimpleStep.Visible = true;
                            tsmSharedStep.Visible = true;
                        }
            }
        }

        private void workItemGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (workItemGridView.CurrentCell.ColumnIndex == 0 && workItemGridView.CurrentCell.ReadOnly == false)
            {
                var form = new AttachmentForm(Data);
                form.Show();
            }
            formChanged = true;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.C | Keys.Control:
                    {
                        Enabled = false;
                        var args = new ExportEventArgs(Data);

                        var evnt = CopyRows;
                        if (evnt != null)
                            evnt(this, args);
                        Enabled = true;
                        break;
                    }
                case Keys.V | Keys.Control:
                    {
                        Enabled = false;
                        var args = new ExportEventArgs(Data);

                        var evnt = PasteRows;
                        if (evnt != null)
                            evnt(this, args);
                        formChanged = true;
                        Enabled = true;
                        break;
                    }
                case Keys.F | Keys.Control:
                    {
                        FindTextForm form = new FindTextForm();
                        form.Data = Data;
                        if (form.ShowDialog(this) == DialogResult.OK)
                            form.Close();
                        return true;
                    }
            }
            return false;
        }

        private void MainFormFormClosing(object sender, FormClosingEventArgs e)
        {
            if (formChanged)
            {
                DialogResult result = MessageBox.Show(@"Do you want to save the work item?", @"Work Item Has Changed",
                                                      MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    Data = WorkItems.Save(Data);
                    formChanged = false;
                }
                if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }

        #endregion

        private void LoadForm()
        {
            InitializeComponent();
            Data = new SharedData();
            if (Data.TestProject != null)
                projectLabel.Text = Data.TfsProjectCollection.Name + @"\" + Data.TestProject.WitProject.Name;
            testCaseNamelabel.Text = "";
            areaLabel.Text = "";
            startReleaseLabel.Text = "";
            endReleaseLabel.Text = "";
            toolTip.SetToolTip(loadWorkItemButton, "Refresh/Load Work Item");
            toolTip.SetToolTip(insertStepButton, "Add New Step");
            toolTip.SetToolTip(deleteStepButton, "Remove Step");
            toolTip.SetToolTip(saveWorkItemButton, "Save Work Item");
            toolTip.SetToolTip(projectButton, "Change Project");
            toolTip.SetToolTip(addSharedStepsButton, "Add Shared Step");
            toolTip.SetToolTip(newButton, "Open New Test Case/Shared Step");
            contextMenuStrip.Visible = false;
            Data.GridView = workItemGridView;
            Data.GroupIndexer = 0;
            Text = Text + @" Total Steps " + workItemGridView.Rows.Count;
        }

        #endregion

        public void SetLabels(WorkItemAttributes workItemAttributes)
        {
            testCaseNamelabel.Text = Data.WorkItemAttributes.Name;
            areaLabel.Text = Data.WorkItemAttributes.Area;
            if (Data.WorkItemAttributes.StartRelease != null)
            {
                startReleaseLabel.Text = Data.WorkItemAttributes.StartRelease;
            }
            else
            {
                label1.Visible = false;
            }

            if (Data.WorkItemAttributes.EndRelease != null)
            {
                endReleaseLabel.Text = Data.WorkItemAttributes.EndRelease;
            }
            else
            {
                label2.Visible = false;
            }
        }
        #endregion
    }

    public class ExportEventArgs : EventArgs
    {
        public SharedData Data { get; private set; }
        public ExportEventArgs(SharedData data)
        {
            Data = data;
        }
    }
}